package com.wejoy.video.middle.station.data.service.res.impl;

import com.wejoy.video.middle.station.data.domain.res.PhotoResLib;
import com.wejoy.video.middle.station.data.enums.dict.EnumStatus;
import com.wejoy.video.middle.station.data.enums.dict.MultiMediaUploaderType;
import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.mapper.res.IPhotoResLibMapper;
import com.wejoy.video.middle.station.data.service.common.IIdWorkerService;
import com.wejoy.video.middle.station.data.service.file.IFileService;
import com.wejoy.video.middle.station.data.service.res.IPhotoResLibService;
import com.wejoy.video.middle.station.data.util.FileUtils;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.file.UploadFileVO;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * 图片资源库
 *
 * @author Administrator
 * @date 2021年10月20日 18:11:17
 */
@Service
public class PhotoResLibServiceImpl implements IPhotoResLibService {
    private final static Logger logger = LoggerFactory.getLogger(PhotoResLibServiceImpl.class);
    @Autowired
    private IPhotoResLibMapper photoResLibMapper;
    @Autowired
    private IIdWorkerService idWorkerService;
    @Autowired
    private IFileService fileService;

    @Override
    public void save(PhotoResLib photoResLibReq, MultipartFile imgFile, String base64Url) {
        if (null == photoResLibReq.getId() && imgFile == null && StringUtils.isBlank(base64Url)) {
            throw new BusinessException("请上传图片！");
        }
        MultipartFile base64file = null;
        PhotoResLib dbPhotoResLibDB = null;
        if (null == photoResLibReq.getId()) {
            PhotoResLib queryCondition = new PhotoResLib();
            queryCondition.setId(photoResLibReq.getId());
            dbPhotoResLibDB = photoResLibMapper.getOne(queryCondition);
        }
        if (StringUtils.isNotBlank(base64Url)) {
            //把base64转换成文件
            base64file = base64UrltoFile(base64Url);
            //上传剪辑后的图片
            buildPhotoResLib(photoResLibReq, base64file);
            if (StringUtils.isBlank(photoResLibReq.getFileName())) {
                photoResLibReq.setFileName(StringUtils.uuid());
            }
        } else if (imgFile != null && !imgFile.isEmpty()) {
            buildPhotoResLib(photoResLibReq, imgFile);
            if (StringUtils.isNotBlank(photoResLibReq.getFileName())) {
                photoResLibReq.setFileName(photoResLibReq.getFileName());
            }
        } else
            //没有重新上传图片 和 裁剪图片时
            if (StringUtils.isNotBlank(photoResLibReq.getFileName())) {
                photoResLibReq.setFileName(photoResLibReq.getFileName());
            } else {
                photoResLibReq.setFileName(photoResLibReq.getFileName());
            }
        //暂时默认上传者为内部上传者类型
        photoResLibReq.setUploaderType(MultiMediaUploaderType.INNER_UPLOADER.getCode());
        if (null == dbPhotoResLibDB) {
            insertSelective(photoResLibReq);
        } else {
            updateSelectiveById(photoResLibReq);
        }
    }

    @Override
    public void save(PhotoResLib req, String operator) {
        req.setOperator(operator);
        if (null == req.getId()) {
            insertSelective(req);
        } else {
            updateSelectiveById(req);
        }
    }

    @Override
    public int insertSelective(PhotoResLib req) {
        checkStringLength(req, false);
        req.setId(idWorkerService.getNextId());
        req.setStatus(EnumStatus.NEW.getCode());
        return photoResLibMapper.insertSelective(req);
    }

    @Override
    public int updateSelectiveById(PhotoResLib photoResLib) {
        WJAssert.notNull(photoResLib, "入参对象不能为空");
        WJAssert.notNull(photoResLib.getId(), "id参数错误");
        PhotoResLib where = new PhotoResLib();
        where.setId(photoResLib.getId());
        return photoResLibMapper.updateSelective(photoResLib, where);
    }

    @Override
    public int getCount(PhotoResLib photoResLib) {
        checkStringLength(photoResLib, true);
        return photoResLibMapper.getCount(photoResLib);
    }

    /**
     * 将图片参数数据设置到请求参数中
     *
     * @param photoResLibReq
     * @param base64file
     */
    private void buildPhotoResLib(PhotoResLib photoResLibReq, MultipartFile base64file) {
        UploadFileVO uploadFileVO = uploadFileWithMyRet(base64file);
        if (null == photoResLibReq.getId()) {
            photoResLibReq.setId(idWorkerService.getNextId());
        }
        photoResLibReq.setStatus(EnumStatus.AUDIT.getCode());
        photoResLibReq.setCreateTime(new Date());
        photoResLibReq.setCreateUserId(photoResLibReq.getCreateUserId());
        photoResLibReq.setExtensionName(FileUtils.getSuffix(base64file.getOriginalFilename()));
        photoResLibReq.setFileSize(base64file.getSize());
        photoResLibReq.setImgHeight(uploadFileVO.getHeight().intValue());
        photoResLibReq.setImgWidth(uploadFileVO.getWidth().intValue());
        photoResLibReq.setPath(uploadFileVO.getKey());
    }

    @Override
    public PhotoResLib getOneById(Long id) {
        WJAssert.notNull(id, "id参数错误");
        PhotoResLib where = new PhotoResLib();
        where.setId(id);
        return photoResLibMapper.getOne(where);
    }

    @Override
    public List<PhotoResLib> getList(PhotoResLib photoResLib) {
        checkStringLength(photoResLib, true);
        return photoResLibMapper.getList(photoResLib);
    }

    @Override
    public List<PhotoResLib> getPageList(PhotoResLib photoResLib) {
        checkStringLength(photoResLib, true);
        return photoResLibMapper.getPageList(photoResLib);
    }

    @Override
    public void audit(Long id, String operator) {
        PhotoResLib req = new PhotoResLib();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.AUDIT.getCode());
        updateSelectiveById(req);
    }

    @Override
    public void unaudit(Long id, String operator) {
        PhotoResLib req = new PhotoResLib();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.NEW.getCode());
        updateSelectiveById(req);
    }

    @Override
    public void delete(Long id, String operator) {
        PhotoResLib req = new PhotoResLib();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.DEL.getCode());
        updateSelectiveById(req);
    }


    /**
     * base64图片数据转文件
     *
     * @param base64Url base64数据
     * @return 文件
     */
    public MultipartFile base64UrltoFile(String base64Url) {
        if (org.apache.commons.lang.StringUtils.isEmpty(base64Url)) {
            throw new BusinessException("图片BASE64错误");
        }
        //过滤base64前缀
        String imgbese64 = base64Url.replace("data:image/png;base64,", "");
        // 图像数据为空
        if (imgbese64 == null) {
            return null;
        }
        MultipartFile file = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgbese64);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            InputStream inputStream = new ByteArrayInputStream(b);
            file = new MultipartFile() {
                @Override
                public String getName() {
                    return "tmp.jpg";
                }

                @Override
                public String getOriginalFilename() {
                    return "tmp.jpg";
                }

                @Override
                public String getContentType() {
                    return ContentType.APPLICATION_OCTET_STREAM.toString().toString();
                }

                @Override
                public boolean isEmpty() {
                    return false;
                }

                @Override
                public long getSize() {
                    return b.length;
                }

                @Override
                public byte[] getBytes() throws IOException {
                    return b;
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return inputStream;
                }

                @Override
                public void transferTo(File dest) throws IOException, IllegalStateException {

                }
            };
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        return file;
    }

    /**
     * 上传单个文件(返回MyRet)
     *
     * @param imgFile 文件
     * @return 文件路径
     * @throws IOException
     */
    @Override
    public UploadFileVO uploadFileWithMyRet(MultipartFile imgFile) {
        try {
            UploadFileVO upload = fileService.upload(EnumUpload.RES_PHOTO_LIB, imgFile.getBytes());
            return upload;
        } catch (IOException e) {
            logger.error("bytes异常", e);
            throw new BusinessException("文件异常");
        }
    }

    @Override
    public PhotoResLib selectPhotoInfoByPath(String imgPath) {
        PhotoResLib photoResLibQuery = new PhotoResLib();
        photoResLibQuery.setPath(imgPath);
        List<PhotoResLib> photoResLibList = photoResLibMapper.getList(photoResLibQuery);
        if (photoResLibList.size() != 0) {
            return photoResLibList.get(0);
        }
        return photoResLibQuery;
    }

    /**
     * 参数校验注解默认使用的方法
     */
    private void checkStringLength(PhotoResLib photoResLib, boolean nullAble) {
        WJAssert.notNull(photoResLib, "入参对象不能为空");
        WJAssert.limitMaxLength(photoResLib.getExtensionName(), nullAble, 10, "扩展名不合法!");
        WJAssert.limitMaxLength(photoResLib.getPath(), nullAble, 255, "图片路径不合法!");
        WJAssert.limitMaxLength(photoResLib.getCreateUserId(), nullAble, 32, "上传用户id不合法!");
        WJAssert.limitMaxLength(photoResLib.getFileName(), nullAble, 255, "文件名不合法!");
        WJAssert.limitMaxLength(photoResLib.getClassificationId(), true, 32, "分类ID不合法!");
        WJAssert.limitMaxLength(photoResLib.getOperator(), true, 100, "操作人不合法!");
        WJAssert.limitMaxLength(photoResLib.getRemark(), true, 255, "备注不合法!");
    }
}
